import { MessageBox, Message ,Loading  } from 'element-ui'
import { uploadPrefix } from '@/consts/consts'

let loading = null 
function startLoading () {
  loading = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
function endLoading () {
  loading.close()
}
export default async (ctx, inject) => {
  const { app, env } = ctx
  const { $axios: axios, router } = app

  var returnConf = async (axios) => {
    const { protocol, host } = window.location
    // let prefix = env.VUE_APP_ENV === 'development' ? '' : '/'
    let prefix = ''
    let res = await axios.get(`${protocol}//${host}/${prefix}/config.json`)
    return res.data.baseUrl
  }
  
  const BaseURL = await returnConf(axios)
  
  // create an axios instance
  const service = axios.create({
    baseURL: BaseURL, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 30000 // request timeout
  })
  // request interceptor
  service.interceptors.request.use(
    config => {
      // do something before request is sent
      // if (store.getters.access_token) {
      //   // let each request carry token
      //   // ['Access-Token'] is a custom headers key
      //   config.headers['Access-Token'] = ''
      // }
      config.headers['Access-Token'] = localStorage.getItem('access_token') || ''
      return config
    },
    error => {
      console.log('request error:', error) // for debug
      return Promise.reject(error)
    }
  )

  // response interceptor
  service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
    */
    response => {
      const res = response.data
      if (res.code !== 0) {

        if (res.message === '版本号已存在') {
          Message({
            message: res.message,
            type: 'error'
          })
        }
        if (['当前模版仍被引用，不能删除', '请先删除当前模板的相关配置'].includes(res.message)) {
          Message({
            message: res.message,
            type: 'warning'
          })
          return res
        }
        const loginErrCodes = [1017, 4031006, 4041000, 4001011, 4001012, 4031002, 100003]
        const otherErrCodes = [4001003, 5030003, 1012, 1019, 1016]
        if ([...loginErrCodes, ...otherErrCodes].includes(res.code)) { // 登录错误
          Message({
            message: res.message,
            type: 'error'
          })
          return Promise.reject(new Error(res.message || 'Error'))
        }
 
        
        if (res.code === 1015) { // token失效  expired
          console.log('token失效  expired:')
          sessionStorage.setItem('currentMenu', '1')
          router.replace('/')
        }
        console.log('进到这一步---------')
        // Message({
        //   message: res.message,
        //   type: 'error',
        //   duration: 852000
        // })
        return Promise.reject(new Error(res.message || 'Error'))
        
      } else {
        return res
      }
    },
    error => {
      console.log('error.response', error.response)
      // const err = error.response.data
      if (error.response.data.code === 4031001) { // token失效  expired
        console.log('process.env.VUE_APP_ENV >>>>>' + process.env.VUE_APP_ENV)
        if (process.env.VUE_APP_ENV === 'production') {
          MessageBox.confirm('身份验证失效，请重新进入', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log('==============token expired==============')
          })
        } else {
          MessageBox.confirm('身份验证失效', '提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            sessionStorage.setItem('currentMenu', '1')
            router.replace('/')
 
          })
        }
      }
      if(error.response.data.code === 4031006){

      }

      return Promise.reject(error)
    }
  )
  ctx.$service = service
  inject('service', service)

  // 下载服务
  const dowloadService = axios.create({
    baseURL: BaseURL, // url = base url + request url
    responseType: 'blob',
    timeout: 30000 // request timeout
  })

  dowloadService.interceptors.request.use(
    config => {
      config.headers['Access-Token'] = localStorage.getItem('access_token') || ''
      return config
    },
    error => {
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )

  ctx.$dowloadService = dowloadService
  inject('dowloadService', dowloadService)
  
  
  // 上传服务
  const uploadService = axios.create({
    baseURL: `${BaseURL}${uploadPrefix}`,
    timeout: 30000
  })

  uploadService.interceptors.request.use(
    config => {
      config.headers['Access-Token'] = localStorage.getItem('access_token') || ''
      config.headers['Content-Type'] = 'multipart/form-data'

      //startLoading()
      return config
    },
    error => {
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )
  uploadService.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
    */
    response => {
      const res = response.data
      //endLoading()
      if (res.code !== 0) {
        if (res.code === 100003) {
          return res
        }
        
        if (res.code === 1015) { // token失效  expired
          console.log('token失效  expired:')
          sessionStorage.setItem('currentMenu', '1')
          router.replace('/')
        }

        Message({
          message: res.message,
          type: 'error'
        })
        return Promise.reject(new Error(res.message || 'Error'))
        
      } else {
        return res
      }
    },
    error => {
      endLoading()
      console.log('error.response', error.response)
      if (error.response.data.code === 4031001) { // token失效  expired
        console.log('process.env.VUE_APP_ENV >>>>>' + process.env.VUE_APP_ENV)
        if (process.env.VUE_APP_ENV === 'production') {
          MessageBox.confirm('身份验证失效，请重新进入', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log('==============token expired==============')
          })
        } else {
          MessageBox.confirm('身份验证失效', '提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            sessionStorage.setItem('currentMenu', '1')
            router.replace('/')
 
          })
        }
      }
      return Promise.reject(error)
    }
  )

  ctx.$uploadService = uploadService
  inject('uploadService', uploadService)
}
